package com.bw.zonghe0719.Login

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.mvvm.BaseActivity
import com.bw.zonghe0719.R
import com.bw.zonghe0719.databinding.ActivityLoginBinding

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Route(path = "/app/Login/LoginActivity")
class LoginActivity :BaseActivity<ActivityLoginBinding, LoginViewModel>(){
    override fun initView() {
        binding.getYzm.isEnabled=false
        binding.etUsername.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
               if(s!=null&&s.length==11){
                   binding.getYzm.isEnabled=true
               }
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        //点击获取验证码
        binding.getYzm.setOnClickListener {
            var usernameval=binding.etUsername.text.toString()
            if(usernameval.isEmpty()){
                ToastUtils.showLong("用户名不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileExact(usernameval)){
                ToastUtils.showLong("用户名格式错误")
                return@setOnClickListener
            }
            viewModel.codeSend(usernameval)
        }
        binding.cb.setOnClickListener {
            if(binding.cb.isChecked){
                binding.btnLogin.isEnabled=true
            }else{
                binding.btnLogin.isEnabled=false
            }
        }
        //点击登录按钮 实现登录功能
        binding.btnLogin.setOnClickListener {
            //判断非空
            var usernameval=binding.etUsername.text.toString()
            var codeval=binding.yzm.text.toString()
            if(usernameval.isEmpty()||codeval.isEmpty()){
                ToastUtils.showLong("输入框不能为空")
            }else{
                if(RegexUtils.isMobileExact(usernameval)){
                    viewModel.loginCode(codeval,usernameval)
                }else{
                    ToastUtils.showLong("用户名格式错误")
                }
            }
        }
        //点击账号密码登录
        binding.goLogin.setOnClickListener {
            startActivity(Intent(this@LoginActivity, LoginPwdActivity::class.java))
        }
        //富文本
        var s = binding.fwb.text.toString()
        var spannableStringBuilder = SpannableStringBuilder(s)
        var clienkSpannable1=object :ClickableSpan(){
            override fun onClick(widget: View) {
//                ARouter.getInstance().build("/app/utils/WebViewActivity")
//                    .withString("url","https://m.qfang.com/shenzhen/user/user-protocol.html").navigation()

                showAlert("这是用户协议")
            }
        }
        spannableStringBuilder.setSpan(clienkSpannable1,7,13,SpannableStringBuilder.SPAN_INTERMEDIATE)
        var clienkSpannable2=object :ClickableSpan(){
            override fun onClick(widget: View) {
//                ARouter.getInstance().build("/app/utils/WebViewActivity")
//                    .withString("url","https://m.qfang.com/shenzhen/user/privacy-protocol.html").navigation()

                showAlert("这是隐私政策")
            }
        }
        spannableStringBuilder.setSpan(clienkSpannable2,14,20,SpannableStringBuilder.SPAN_INTERMEDIATE)
        binding.fwb.movementMethod=LinkMovementMethod.getInstance()
        binding.fwb.text=spannableStringBuilder
    }
    fun showAlert(s:String){
        AlertDialog.Builder(this)
            .setTitle("提示:")
            .setMessage(s)
            .setNegativeButton("取消"){a,b->
                binding.cb.isChecked=false
                binding.btnLogin.isEnabled=false
            }
            .setPositiveButton("确定"){a,b->
                binding.cb.isChecked=true
                binding.btnLogin.isEnabled=true
            }
            .show()
    }

    @SuppressLint("NewApi", "NotificationPermission")
    override fun initData() {
        viewModel.codeSendSuccess.observe(this){
            if(it.code==200){
                //发送通知
                var manager =getSystemService(NOTIFICATION_SERVICE) as NotificationManager
                manager.createNotificationChannel(NotificationChannel("ch1", "通道1", NotificationManager.IMPORTANCE_DEFAULT))
                var notification = Notification.Builder(this, "ch1")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("通知:")
                    .setContentText("登录验证码:${it.data.content.substring(8,14)}")
                    .build()
                manager.notify(1,notification)
                //开启倒计时
                binding.getYzm.isEnabled=false
                lifecycleScope.launch {
                    for (i in 10 downTo 1) {
                        binding.getYzm.text="${i}s后可再次获取"
                        delay(1000)
                    }
                    binding.getYzm.isEnabled=true
                    binding.getYzm.text="获取验证码"
                }
            }
        }
        //验证码登录结果
        viewModel.loginCodeSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                SPUtils.getInstance().apply {
                    put("token",it.data.token)
                    put("phone",it.data.phone)
                }
                //跳转用户页面
                startActivity(Intent(this@LoginActivity, UserActivity::class.java))
            }
        }
    }

    override fun getViewModel(): Class<LoginViewModel> {
        return LoginViewModel::class.java
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_login
    }
}